using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace OpenComposite.Base
{
	[ToolboxBitmap(typeof(Panel)),
	ToolboxItem(true)]
	public class GradientPanel : Panel
	{
		public GradientPanel()
		{
			SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);

			_brush = new LinearGradientBrush(this.ClientRectangle, this.BackColor, this.BackColor2,
											 this.LinearGradientMode);

			this.BackColorChanged += new EventHandler(GradientPanel_BackColorChanged);
			this.Resize += new EventHandler(GradientPanel_Resize);
			this.Paint += new PaintEventHandler(GradientPanel_Paint);
		}

		protected override void Dispose(bool disposing)
		{
			if ( disposing ) {
				if ( _brush != null ) {
					_brush.Dispose();
					_brush = null;
				}
			}
			base.Dispose(disposing);
		}

		[Category("Appearance")]
		[DefaultValue(typeof(Color), "RoyalBlue")]
		public Color BackColor2
		{
			get { return _bgcolor2; }
			set
			{
				_bgcolor2 = value;
				updateBrush();
			}
		}
		[Category("Appearance")]
		[DefaultValue(LinearGradientMode.Vertical)]
		public LinearGradientMode LinearGradientMode
		{
			get { return _gradientMode; }
			set
			{
				_gradientMode = value;
				updateBrush();
			}
		}
		private LinearGradientBrush _brush;
		private Color _bgcolor2 = Color.RoyalBlue;
		private LinearGradientMode _gradientMode = LinearGradientMode.Vertical;

		private void updateBrush()
		{
			if ( this.ClientRectangle.Width == 0 || this.ClientRectangle.Height == 0 ) {
				return;
			}

			if ( _brush != null ) _brush.Dispose();

			_brush = new LinearGradientBrush(this.ClientRectangle, this.BackColor, this.BackColor2,
											 this.LinearGradientMode);
			this.Refresh();
		}

		void GradientPanel_Resize(object sender, EventArgs e)
		{
			updateBrush();
		}

		void GradientPanel_BackColorChanged(object sender, EventArgs e)
		{
			updateBrush();
		}

		private void GradientPanel_Paint(object sender, PaintEventArgs e)
		{
			e.Graphics.FillRectangle(_brush, this.ClientRectangle);
		}
	}
}
